<!--
 * @Author: jiangyg email@jiangyg.com
 * @Date: 2022-08-14 15:31:12
 * @LastEditors: jiangyg email@jiangyg.com
 * @LastEditTime: 2022-11-19 17:47:27
 * @FilePath: /frontend/mall-frontend/src/views/modules/admin/common/category-cascader.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <el-cascader v-model="defaultValue" ref="cascaderRef" placeholder="请选择分类" 
            @change="handleChangeEvent" style="width: 100%" clearable :options="categorys" 
            :props="cascaderProps" filterable> </el-cascader>
</template>

<script lang="ts" setup>
import http from "@/utils/httpRequest";
import { ref, onMounted, reactive } from "vue";

// 属性定义
const props = defineProps({
  modelValue: {
    type: Array,
    required: false,
  },
});

const cascaderProps = reactive({
  value: "id",
  label: "name",
  children: "children",
  expandTrigger: "hover",
});

const categorys = ref([]);

const defaultValue = ref([]);

const cascaderRef = ref();

// 父级组件的自定义事件
const emit = defineEmits(['update:modelValue']);

// 组件挂载完成后执行
onMounted(() => {
  defaultValue.value = props.modelValue;
  // 清空
  clearCheckedNodes();
  // 初始化数据
  http
    .post({
      url: "/product/category/mtree",
    })
    .then(({ data }) => {
      categorys.value = http.success(data) ? data.body : [];
    });
});

// 事件变化
const handleChangeEvent = (val) => {
  emit("update:modelValue", val);
};

// 清空选择数据
const clearCheckedNodes = () => {
  if (cascaderRef && cascaderRef.value) {
    cascaderRef.value.panel.clearCheckedNodes();
  }
};

// 暴露方法
defineExpose({ clearCheckedNodes });
</script>
